package DaraSourceText;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 */
public class Text {
    public static void main(String[] args) {
        //1.建立数据库源
        MysqlDataSource mysqlDataSource =new MysqlDataSource();
        //设置数据库连接串
        mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/java?characterEncoding=utf8");
        //用户名
        mysqlDataSource.setUser("root");
        //密码
        mysqlDataSource.setPassword("123456");
        //2.定义JDBC的数据源
        DataSource dataSource =mysqlDataSource;
        //定义全局变量，利于最后关闭
        Connection connection =null;
        PreparedStatement statement =null;
        ResultSet resultSet =null;
        try {
            //3.建立数据库连接
            connection =dataSource.getConnection();
            //获取预编译的sql语句
            String sql = "select student_id,sn,name,mail from student where name =?";
            //4.创建Statement
             statement =connection.prepareStatement(sql);
            //用户输入数据
            System.out.println("请输入姓名：");
            Scanner scanner =new Scanner(System.in);
            String name =scanner.next();
            //5.用真实值代替占位符
            statement.setString(1,name);
            resultSet = statement.executeQuery();
            //6.遍历结果集
            while (resultSet.next()){
                long stuId = resultSet.getLong(1);
                String stuSn = resultSet.getString(2);
                String stuName = resultSet.getString(3);
                String stuMail = resultSet.getString(4);
                System.out.println(MessageFormat.format
                        ("学生编号={0},学号={1},姓名={2},邮件={3}",stuId,stuSn,stuName,stuMail));

            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //7.依次释放资源，关闭连接
            if (resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (statement!=null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
